package net.pinnoocle.playcommon.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author ye
 * @Description
 * @create 2021-09-14 20:59
 */
@Slf4j
public class OssFileUtil {

    /**
     * 上传图片到阿里云.
     */
    public static String uploadPicture(MultipartFile file, String path,Map<String,String> offConfigMap) {
        final List<String> contentTypes = Arrays.asList("image/jpeg", "image/gif", "image/png");
        //校验文件类型
        String contentType = file.getContentType();
        if (!contentTypes.contains(contentType)) {
            return null;
        }
        return uploadFileToOss(file, path,"image/jpg",offConfigMap);
    }

    private static String uploadFileToOss(MultipartFile file,String path,String contentType, Map<String,String> offConfigMap) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = offConfigMap.get("endpoint");
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。
        String accessKeyId = offConfigMap.get("access_key");
        String accessKeySecret = offConfigMap.get("secret_key");
        String bucketName = offConfigMap.get("bucket_name");
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        InputStream inputStream = null;
        String fileName = path + HelpUtils.getUUID() + file.getOriginalFilename();
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // meta设置请求头
        ObjectMetadata meta = new ObjectMetadata();
        //meta.setContentType("image/jpg");
        meta.setContentType(contentType);
        // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（fileName）。
        ossClient.putObject(bucketName, fileName, inputStream,meta);
        // 关闭OSSClient。
        ossClient.shutdown();
        //return "https://" + bucketName + "." + endpoint + "/" + fileName;
        return endpoint + "/" + fileName;
    }
}
